package com.softer.chengxin.corp.dao.provider;

import com.softer.chengxin.common.domin.Page;
import com.softer.chengxin.common.enums.NumberEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;

/**
 * @author Gong Zhiyang
 * @date 2018/10/8
 */
public class CorpDaoProvider {
    /**
     * 获取管理下的企业信息数量
     *
     * @param map map
     * @return sql
     */
    public String getCorpListNum(HashMap<String, Object> map) {
        StringBuffer sql = new StringBuffer(20);
        String area = (String) map.get("area");
        String state = (String) map.get("state");
        String name = (String) map.get("name");
        String provinceCompany = (String) map.get("provinceCompany");
        sql.append("SELECT count(*) FROM company_base_info WHERE state IN (1, 2, 3,4,5,6)");
        commonSql(sql, area, state, name,provinceCompany);
        return sql.toString();
    }

    /**
     * 查询企业集合
     *
     * @return
     */
    public String getCorpList(HashMap<String, Object> map) {
        StringBuffer sql = new StringBuffer(20);
        Page page = (Page) map.get("page");
        String area = (String) map.get("area");
        String name = (String) map.get("name");
        String state = (String) map.get("state");
        String provinceCompany = (String) map.get("provinceCompany");
        sql.append("SELECT id, qy_no AS qyNo, `name`, province,city,district,street,community,register_address as registerAddress,");
        sql.append("DATE_FORMAT(gmt_modified, '%Y-%m-%d') AS gmtCreate, state FROM company_base_info WHERE state IN (1, 2, 3,4,5,6)");
        commonSql(sql, area, state, name ,provinceCompany);
        sql.append(" LIMIT ");
        sql.append(page.getBeginIndex()).append(",").append(page.getLimit());
        return sql.toString();
    }

    public void commonSql(StringBuffer sql, String area, String state, String name ,String provinceCompany) {
        if (StringUtils.isNotBlank(area)) {
            sql.append(" and (CASE community WHEN 0 THEN street in (").append(area).append(") ELSE community in (").append(area).append(") end)");
        }
        if (StringUtils.isNotBlank(state)) {
            sql.append(" and state in (").append(state).append(")");
        }
        if (StringUtils.isNotBlank(name)) {
            sql.append(" and instr(name,#{name})>0");
        }
        if (StringUtils.isNotBlank(provinceCompany)) {
            //1省内   0省外
            if(String.valueOf(NumberEnum.ONE.getNum()).equals(provinceCompany)){
                sql.append(" and province_company = #{provinceCompany} ");
            }else if(String.valueOf(NumberEnum.ZERO.getNum()).equals(provinceCompany)){
                sql.append(" OR (state IN (1) AND  province_company = #{provinceCompany}) ");
            }
        }
    }
}
